import requests   # 数据请求模块
import re     # 正则表达式模块
import json  # 数据类型处理模块
from tqdm import tqdm   #进度条配置
import os    # 处理文件和目录
import subprocess
import time

#proxies = {'http': 'socks5://127.0.0.1:7890', 'https': 'socks5://127.0.0.1:7890'}
proxies = {'https': '127.0.0.1:7890'}
headers = {
    'cookie': 'VISITOR_INFO1_LIVE=9qZVrzB27uI; PREF=f4=4000000&tz=Asia.Shanghai; _ga=GA1.2.621834420.1648121145; _gcl_au=1.1.1853038046.1648121145; NID=511=Zc1APdmEbCD-iqVNVgI_vD_0S3LVI3XSfl-wUZEvvMU2MLePFKsQCaKUlUtchHSg-kWEVMGOhWUbxpQMwHeIuLjhxaslwniMh1OsjVfmOeTfhpwcRYpMgqpZtNQ7qQApY21xEObCvIez6DCMbjRhRQ5P7siOD3X87QX0CFyUxmY; OTZ=6430350_24_24__24_; GPS=1; YSC=0E115KqM_-I; GOOGLE_ABUSE_EXEMPTION=ID=d02004902c3d0f4d:TM=1648620854:C=r:IP=47.57.243.77-:S=YmZXPW7dxbu83bDuauEpXpE; CONSISTENCY=AGDxDeNysJ2boEmzRP4v6cwgg4NsdN4-FYQKHCGhA0AeW1QjFIU1Ejq1j8l6lwAc6c-pYTJiSaQItZ1M6QeI1pQ3wictnWXTOZ6_y8EKlt0Y_JdakwW6srR39-NLuPgSgXrXwtS0XTUGXpdnt4k3JjQ',
    'referer': 'https://www.youtube.com',
    'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/99.0.4844.84 Safari/537.36'
}
ffmpegurl='/opt/homebrew/bin/ffmpeg'

##################

def mymkdir(filepath):
    #print(type(filepath))
    filepath = filepath.strip()
    filepath = filepath.rstrip("\\")
    isExists = os.path.exists(filepath)
    if isExists:
        #print(filepath + ' 目录已存在')
        return False
    else:
        os.makedirs(filepath)
        print('创建成功')
        return True

def combineVideoAudio(videopath,audiopath,outpath):
    print(ffmpegurl+" -loglevel quiet -i " + videopath + " -i " + audiopath + " -c copy "+ outpath)
    subprocess.call((ffmpegurl+" -loglevel quiet -i " + videopath + " -i " + audiopath + " -c copy "+ outpath).encode("utf-8").decode("utf-8"),shell=True)
    #os.remove(videopath)
    #os.remove(audiopath)

 
def downloadfile(file_url,file_path):
    fileinfo = requests.get(file_url, stream=True,proxies=proxies)
    file_size = int(fileinfo.headers.get('Content-Length'))
    video_pbar = tqdm(total=file_size)

    with open(file_path, mode='wb') as f:
        # 把视频分成 1024 * 1024 * 2 为等分的大小 进行遍历
        for video_chunk in fileinfo.iter_content(1024*1024*2):
            # 写入数据
            f.write(video_chunk)
            # 更新进度条
            video_pbar.set_description(f'正在下载{file_path}中......')
            # 更新进度条长度
            video_pbar.update(1024*1024*2)
        # 下载完毕
        video_pbar.set_description('下载完成！')
        # 关闭进度条
        video_pbar.close()   


if __name__=='__main__':
    url = 'https://www.youtube.com/watch?v=ExqqdUXXdgA'
    response = requests.get(url=url, headers=headers)
    #print(response.text)

    json_str = re.findall('var ytInitialPlayerResponse = (.*?);var', response.text)[0]
    json_data = json.loads(json_str)

    video_url = json_data['streamingData']['adaptiveFormats'][0]['url']
    audio_url = json_data['streamingData']['adaptiveFormats'][-2]['url']
    videoId=json_data['videoDetails']['videoId']
    title = json_data['videoDetails']['title']  
    title = title.replace(' ', '')
    title = re.sub(r'[\/:|?*"<>]', '', title)
    print(video_url)
    print(audio_url)
    print(title)

    timepath=time.strftime('%Y/%m/%d/')
    timepath=r'./'+timepath+'video/youtube/'

    downloadfile(video_url,timepath+videoId+'_video.mp4')
    downloadfile(audio_url,timepath+videoId+'_audio.mp3')
    combineVideoAudio(timepath+videoId+'_video.mp4',timepath+videoId+'_audio.mp4',timepath+title+'.mp4')


